import { getPhoneCode, login, resetPassword } from '@/services/login';
import {
  ArrowLeftOutlined,
  LockOutlined,
  MobileOutlined,
  ExclamationCircleOutlined
} from '@ant-design/icons';
import {
  LoginForm,
  ProFormCaptcha,
  ProFormText,
  ProFormCheckbox
} from '@ant-design/pro-components';
import { history, useModel } from '@umijs/max';
import { Form, message, Tabs, Checkbox, Modal } from 'antd';
import { useState } from 'react';
import styles from './index.less'

type LoginType = 'check_code' | 'password';

export default () => {
  const [loginType, setLoginType] = useState<LoginType>('password');
  const [forgetPWD, setForgetPWS] = useState(false);
  const [resetLoading, setResetLoading] = useState(false);
  const [form] = Form.useForm();
  const { initialState, setInitialState } = useModel('@@initialState');
  const [checkedVal, setCheckedVal] = useState(false);


  const renderCaptcha = () => {
    return (
      <>
        <ProFormText
          fieldProps={{
            size: 'large',
            prefix: <MobileOutlined className={'prefixIcon'} />,
          }}
          label="手机号"
          name="phoneNum"
          placeholder={'手机号'}
          rules={[
            {
              required: true,
              message: '请输入手机号！',
            },
            {
              pattern: /^1\d{10}$/,
              message: '手机号格式错误！',
            },
          ]}
        />
        <ProFormCaptcha
          fieldProps={{
            size: 'large',
            prefix: <LockOutlined className={'prefixIcon'} />,
          }}
          label="验证码"
          captchaProps={{
            size: 'large',
          }}
          placeholder={'请输入验证码'}
          captchaTextRender={(timing, count) => {
            if (timing) {
              return `${count} ${'获取验证码'}`;
            }
            return '获取验证码';
          }}
          name="captcha"
          rules={[
            {
              required: true,
              message: '请输入验证码！',
            },
          ]}
          onGetCaptcha={async () => {
            await getPhoneCode(form.getFieldValue('phoneNum')).then(() => {
              message.success('发送成功');
            });
          }}
        />
      </>
    );
  };

  const goReg = () => {
    history.push('/reg');
  }

  const changCheck = (val) => {
    // console.log('88888', val)
    setCheckedVal(val.target.checked)
  }

  return (
    <div className={styles.bg_center}>
      <div className={`${styles.content} bg-white rounded-xl overflow-hidden`}>
        {!forgetPWD && (
          <LoginForm
            title="欢迎使用腾云人资"
            layout="vertical"
            onFinish={async (value) => {
              await form.validateFields();
              if (!checkedVal) {
                Modal.confirm({
                  title: '温馨提示',
                  icon: <ExclamationCircleOutlined />,
                  content: '确认已阅读并同意《服务协议》和《隐私政策》',
                  okText: '确认',
                  cancelText: '取消',
                  onOk: () => {
                    setCheckedVal(true)

                    return login({
                      mobile: value.phoneNum,
                      loginMethod: loginType,
                      clientFrom: 'pc_web_2',
                      password: value.password,
                      rememberMe: true,
                      checkCode: value.captcha,
                    }).then(async (loginRes: any) => {
                      if (loginRes.success) {
                        const res = await initialState?.getInitialUserInfo?.();
                        await setInitialState((state) => {
                          return {
                            ...state,
                            currentUser: res.currentUser,
                            accountInfo: res.accountInfo,
                          };
                        });
                        message.success('登陆成功');
                        history.push('/dashboard');
                      } else {
                        message.error(loginRes.resultMessage);
                      }
                    });
                  }
                });
              } else {
                return login({
                  mobile: value.phoneNum,
                  loginMethod: loginType,
                  clientFrom: 'pc_web_2',
                  password: value.password,
                  rememberMe: true,
                  checkCode: value.captcha,
                }).then(async (loginRes: any) => {
                  if (loginRes.success) {
                    const res = await initialState?.getInitialUserInfo?.();
                    await setInitialState((state) => {
                      return {
                        ...state,
                        currentUser: res.currentUser,
                        accountInfo: res.accountInfo,
                      };
                    });
                    message.success('登陆成功');
                    history.push('/dashboard');
                  } else {
                    message.error(loginRes.resultMessage);
                  }
                });
              }

            }}
            form={form}
            actions={
              <div
                style={{
                  marginBlockEnd: 24,
                }}
              >
                <Checkbox checked={checkedVal} onChange={changCheck} name="autoLogin">
                  已阅读并同意《服务协议》和《隐私政策》
                </Checkbox>
                <p
                  style={{
                    fontSize: '12px',
                    color: '#00bdff',
                  }}>
                  <a
                    onClick={goReg}
                  >
                    没有账号？前往注册
                  </a>
                  <a
                    style={{ float: 'right' }}
                    onClick={() => {
                      setForgetPWS(true);
                    }}
                  >
                    忘记密码
                  </a>
                </p>
              </div>
            }

          >
            <Tabs
              className="mt-4"
              centered
              activeKey={loginType}
              onChange={(activeKey) => {
                setLoginType(activeKey as LoginType);
              }}
            >
              <Tabs.TabPane key={'password'} tab={'密码登录'} />
              <Tabs.TabPane key={'check_code'} tab={'验证码登陆'} />
            </Tabs>
            {loginType === 'password' && (
              <>
                <ProFormText
                  name="phoneNum"
                  label="手机号"
                  fieldProps={{
                    size: 'large',
                    prefix: <MobileOutlined className={'prefixIcon'} />,
                  }}
                  placeholder={'手机号'}
                  rules={[
                    {
                      required: true,
                      message: '请输入手机号',
                    },
                    {
                      pattern: /^1\d{10}$/,
                      message: '手机号格式错误！',
                    },
                  ]}
                />
                <ProFormText.Password
                  name="password"
                  placeholder={'密码'}
                  label="密码"
                  fieldProps={{
                    size: 'large',
                    prefix: <LockOutlined className={'prefixIcon'} />,
                  }}
                  rules={[
                    {
                      required: true,
                      message: '请输入密码！',
                    },
                  ]}
                />
              </>
            )}
            {loginType === 'check_code' && renderCaptcha()}
            {/* <div className="my-4 text-end">
              <span
                className="cursor-pointer"
                onClick={() => {
                  setForgetPWS(true);
                }}
              >
                忘记密码
              </span>
            </div> */}

          </LoginForm>
        )}
        {forgetPWD && (
          <div>
            <div className="mt-5 ml-3">
              <ArrowLeftOutlined
                className="cursor-pointer"
                onClick={() => {
                  setForgetPWS(false);
                }}
              />
              <span className="ml-3">找回密码</span>
            </div>
            <LoginForm
              layout="vertical"
              onFinish={(value) => {
                setResetLoading(true);
                resetPassword({
                  checkCode: value.captcha,
                  password: value.password,
                  mobile: value.phoneNum,
                  repeatPassword: value.repeatPassword,
                })
                  .then((res: any) => {
                    if (res.success) {
                      message.success('修改成功');
                      setForgetPWS(false);
                    } else {
                      message.error(res.resultMessage);
                    }
                  })
                  .finally(() => {
                    setResetLoading(false);
                  });
              }}
              submitter={{
                searchConfig: { submitText: '提交' },
                submitButtonProps: { loading: resetLoading },
              }}
              form={form}

            >
              {renderCaptcha()}
              <ProFormText.Password
                name="password"
                label="新密码"
                fieldProps={{
                  size: 'large',
                  prefix: <LockOutlined className={'prefixIcon'} />,
                }}
                placeholder={'请输入新密码'}
                rules={[
                  {
                    required: true,
                    message: '请输入新密码',
                  },
                ]}
              />
              <ProFormText.Password
                name="repeatPassword"
                label="确认新密码"
                fieldProps={{
                  size: 'large',
                  prefix: <LockOutlined className={'prefixIcon'} />,
                }}
                placeholder={'请再次输入新密码'}
                rules={[
                  {
                    required: true,
                    validator(rule, value, callback) {
                      if (!value) {
                        return callback('请再次输入新密码');
                      }
                      if (value !== form.getFieldValue('password')) {
                        return callback('密码不一致');
                      }
                      return callback();
                    },
                  },
                ]}
              />
            </LoginForm>
          </div>
        )}
      </div>
    </div>

  );
};
